#include <windows.h>
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace std;

#include <wx/wx.h>
#include <wx/webrequest.h>

#define _(str) wxT(str)
#include "MainFrame.cpp"

class MyFrame : public MainFrame
{
public:
    MyFrame( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 500,300 ), long style = wxDEFAULT_FRAME_STYLE|wxTAB_TRAVERSAL );
    ~MyFrame();
    json m_cfg;
    wxString m_hosts;
    wxWebRequest m_currentRequest;
    void ReadData(wxCommandEvent &evt);
    void WriteHosts(wxCommandEvent &evt);    
    void WebRequestState(wxWebRequestEvent& evt);
    void addcfg(wxCommandEvent &evt);
    void delcfg(wxCommandEvent &evt);
    void readcfg();
    void writecfg();
};
void MyFrame::readcfg()
{
    // 打开文件并读取内容
    ifstream m_file("config.json");
    if (m_file.is_open()) {
        m_cfg = json::parse(m_file);
        m_file.close();
    } else {
        //wxMessageBox("无法打开config.json文件，正在创建新文件");
        // 创建默认配置
        m_cfg = json::object();
        m_cfg["address"] = json::array();
        m_cfg["address"].push_back("https://github.moeyy.xyz/https://github.com/Clov614/SteamHostSync/blob/main/Hosts");
        
        // 创建并保存新文件
        ofstream new_file("config.json");
        if (new_file.is_open()) {
            new_file << m_cfg.dump(4);
            new_file.close();
            //wxMessageBox("已创建新的config.json文件");
        } else {
            //wxMessageBox("无法创建新的config.json文件");
            this->Close();
        }
    }
    m_cmbox_address->Clear();
    for (const auto& addr : m_cfg["address"]) {
        std::string addrStr = addr.get<std::string>();
        m_cmbox_address->Append(wxString(addrStr.c_str(), wxConvUTF8));    
    }
    m_cmbox_address->SetSelection(0);
}
void MyFrame::writecfg()
{
    ofstream m_file("config.json");
    if (m_file.is_open()) {
        m_file << m_cfg.dump(4); // 使用4个空格进行缩进，美化输出
        m_file.close();
    } else {
        std::cerr << "无法打开文件进行写入" << std::endl;
    }
}
void MyFrame::addcfg(wxCommandEvent &evt){
    m_cfg["address"].push_back(m_cmbox_address->GetValue().ToStdString());
    writecfg();
    readcfg();
}
void MyFrame::delcfg(wxCommandEvent &evt)
{
    wxString selected = m_cmbox_address->GetValue().Trim();
    if (selected.IsEmpty()) {
        wxMessageBox(_("地址不能为空"), _("错误"), wxICON_ERROR | wxOK);
        return;
    }

    std::string selectedStd = selected.ToStdString();

    // 遍历并删除匹配项
    auto& addresses = m_cfg["address"];
    bool found = false;
    for (auto it = addresses.begin(); it != addresses.end(); ++it) {
        if (*it == selectedStd) {
            addresses.erase(it);
            found = true;
            break;
        }
    }

    if (found) {
        writecfg();  // 写入文件
        readcfg();   // 刷新下拉框
    } else {
        wxMessageBox(_("未找到该地址"), _("提示"));
    }
}
void MyFrame::WebRequestState(wxWebRequestEvent& evt)
{
    //wxMessageBox("WebRequestState");
    m_btn_read->Enable(evt.GetState() != wxWebRequest::State_Active);

    switch (evt.GetState())
        {
            case wxWebRequest::State_Completed:
                m_txt_Data->SetValue(evt.GetResponse().AsString());
                break;

            case wxWebRequest::State_Failed:
                wxMessageBox("Web Request failed: %s", evt.GetErrorDescription());
                break;

            case wxWebRequest::State_Cancelled:
                break;

            case wxWebRequest::State_Unauthorized:
                break;

            case wxWebRequest::State_Active:
                break;

            case wxWebRequest::State_Idle:
                // Nothing special to do for this state.
                break;
        }

        
}
void MyFrame::ReadData(wxCommandEvent &evt)
{ 
    //wxMessageBox("ReadData");
    wxString address = this->m_cmbox_address->GetValue().Trim(); // 获取并去除前后空格
    if (address.IsEmpty()) {
        wxMessageBox(_("地址不能为空"), _("错误"), wxICON_ERROR | wxOK); // 提示错误
        return;
    }
    m_currentRequest = wxWebSession::GetDefault().CreateRequest(this,
            m_cmbox_address->GetValue());
    Bind(wxEVT_WEBREQUEST_STATE, &MyFrame::WebRequestState, this);
    m_btn_read->Disable();
    m_currentRequest.Start();
}

void MyFrame::WriteHosts(wxCommandEvent &evt)
{
    std::string content = m_txt_Data->GetValue().ToStdString();
    std::ofstream hostsFile("C:\\Windows\\System32\\drivers\\etc\\hosts");
    if (hostsFile.is_open()) {
        hostsFile << content;
        hostsFile.close();
        wxArrayString output;
        wxExecute("ipconfig /flushdns", output);        
        wxMessageBox(_("DNS刷新成功!"), _("刷新 DNS 结果"));
    } else {
        wxMessageBox(_("无法打开 hosts 文件进行写入"), _("错误"));
    }
}
MyFrame::MyFrame( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : MainFrame( parent, id, title, pos, size, style )
{
    this->SetSize(wxSize(800, 600));
    this->CenterOnScreen(); // 居中显示

    this->m_btn_read->Bind(wxEVT_BUTTON, &MyFrame::ReadData, this);
    this->m_btn_write->Bind(wxEVT_BUTTON, &MyFrame::WriteHosts, this);
    this->m_btn_addcfg->Bind(wxEVT_BUTTON, &MyFrame::addcfg, this);
    this->m_btn_delcfg->Bind(wxEVT_BUTTON, &MyFrame::delcfg, this);

    readcfg();
    


}


MyFrame::~MyFrame()
{
}




class MyApp : public wxApp
{
public:
    bool OnInit() override;
};

bool MyApp::OnInit()
{
    MyFrame *frame = new MyFrame(nullptr, wxID_ANY, "AutoHosts");
    frame->SetIcon(wxICON(MAINICON));
    frame->Show(true);
    return true;
}

wxIMPLEMENT_APP(MyApp);